/*
 * @Author: kason
 * @Date: 2024-09-10 09:25:42
 * @LastEditors: kason199 727491988@qq.com
 * @LastEditTime: 2025-01-18 16:07:57
 * @Description:
 * @FilePath: \zhxiangfeng\android\app\src\main\java\com\amos\zhxiangfeng\MainActivity.java
 */
package com.amos.zhxiangfeng;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.engine.FlutterShellArgs;
import io.flutter.plugins.GeneratedPluginRegistrant;

import androidx.annotation.NonNull;

import android.os.Bundle;
import android.content.res.Configuration;
import android.util.Log;
import android.view.ViewConfiguration;
import android.view.KeyCharacterMap;
import android.content.Context;
import android.os.Build;
import android.view.View;
import android.app.Activity;
import android.content.res.Resources;
import android.view.DisplayCutout;
import android.view.WindowInsets;
import android.view.WindowMetrics;

import java.io.File;
import java.lang.reflect.Method;

import io.flutter.embedding.engine.FlutterEngine;

import io.flutter.plugin.common.MethodChannel;

import android.view.WindowManager;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;

public class MainActivity extends FlutterActivity {

    private static final String CHANNEL = "com.amos.get/language";
    private Context mcontext;


    public static boolean is64Bit() {
        return Build.SUPPORTED_ABIS.length > 0 && Build.SUPPORTED_ABIS[0].contains("64");
    }

    @NonNull
    @Override
    public FlutterShellArgs getFlutterShellArgs() {
        Log.d("MyFlutterActivity", "getFlutterShellArgs");
        FlutterShellArgs supFA = super.getFlutterShellArgs();
        //isHotFix是用来方便造作是否使用修复so包，会在app的启动页MainActivity中通过intent传进来，so包也是在MainActivity中事先做的存储，存到应用私有目录app_libs目录下
//        if (getIntent().getBooleanExtra("isHotFix", false)) {
        //修复的so包只能放在指定目录下，flutter只会读取这些目录下的so文件，这里测试过放在其它地方都不行
        File dir = this.getDir("libs", Activity.MODE_PRIVATE);
        String libPath = dir.getAbsolutePath() + File.separator + "libapp_hot.so";
        Log.d("MyFlutterActivity", "32 :" + libPath);
        if (is64Bit()) {

            libPath = libPath.replace("libapp_hot.so", "libapp_hot64.so");
            Log.d("MyFlutterActivity", "64 :" + libPath);
        }
        File file = new File(libPath);

        Log.d("MyFlutterActivity", "load new :" + libPath);
        if (file.exists()) {
            Log.d("MyFlutterActivity2", " start load new :" + libPath);
            //这句代码就是关键，aot-shared-library-name这个key值就跟FlutterLoader中libapp.so对应的key值一样，然后指定我们修复后的so包libPath路径，这样就会在初始化flutter页面前flutter就会使用我们新的这个修复so包


            supFA.add("--aot-shared-library-name=" + libPath);
        }
//        }
        return supFA;

//                return super.getFlutterShellArgs().apply {
//            this.add( "--aot-shared-library-name=libfixedapp.so" );
//            this.add( "--aot-shared-library-name=/data/data/com.example.untitled1/libfixedapp.so" )
    }

    /**
     * 获取是否存在NavigationBar
     *
     * @param context
     * @return
     */
    public boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            // hasNavigationBar = rs.getBoolean(id);
            return id > 0 && rs.getBoolean(id);
        }

        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
        }
        return hasNavigationBar;
    }

    @Override
    public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
        GeneratedPluginRegistrant.registerWith(flutterEngine);

        mcontext = this;

        // 日志输出当前语言
        new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), CHANNEL)
                .setMethodCallHandler(
                        (call, result) -> {
                            if (call.method.equals("getApplicationId")) {
                                String applicationId = getApplicationContext().getPackageName();
                                result.success(applicationId);
                            } 
                            else if (call.method.equals("getVersionInfo")) {
                                try {
                                    // 获取 PackageInfo
                                    PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                                    String versionName = pInfo.versionName;
                                    int versionCode = pInfo.versionCode;
            
                                    // 返回结果给 Flutter
                                    result.success(versionCode + "");
                                } catch (PackageManager.NameNotFoundException e) {
                                    // 如果获取失败，返回错误信息
                                    result.error("UNAVAILABLE", "Version information not found", null);
                                }
                            }
                            else if (call.method.equals("getLanguage")) {
                                // int batteryLevel = getBatteryLevel();
                                // 获取当前配置
                                Log.d("method getLanguage", "getLanguage");
                                Configuration config = getResources().getConfiguration();

                                // 获取当前系统语言
                                String currentLanguage = config.locale.getLanguage();

                                // Log.d("Current Language", currentLanguage);
                                // Log.d("Current Language", currentLanguage);
                                // Log.d("Current Language", currentLanguage);
                                // Log.d("Current Language", currentLanguage);

                                result.success(currentLanguage);

                            } else if (call.method.equals("GetCpu64")) {
                                Log.d("method GetCpu64", is64Bit() + "");
                                result.success(is64Bit());
                            } else if (call.method.equals("deleteDownLoadSo")) {
                                try {
                                    // 要删除的文件路径

                                    String filepath = call.argument("filepath");

                                    File destFile = new File(filepath);
                                    Log.d("delete", filepath);
                                    if (destFile.exists()) {
                                        Log.d("delete", "1213");
                                        destFile.delete();
                                        result.success(true);
                                    } else {
                                        result.success(false);
                                    }
                                } catch (Exception e) {
                                    result.success(false);
                                }


                            } else if (call.method.equals("printlog")) {

                                String logstr = call.argument("log");
                                Log.d("printlog", logstr);
                                result.success(true);
                            } else if (call.method.equals("saveDownLoadSo")) {

                                String downpath = call.argument("downpath");
                                String nfilename = "libapp_hot.so";
                                File dir = this.getDir("libs", Activity.MODE_PRIVATE);
                                String libPath = dir.getAbsolutePath() + File.separator + "libapp_hot.so";
                                String npath = downpath + "/libapp_hot.so";
                                if (is64Bit()) {
                                    libPath = libPath.replace("libapp_hot.so", "libapp_hot64.so");
                                    nfilename = "libapp_hot64.so";
                                    npath = downpath + "/libapp_hot64.so";
                                }
                                Log.d("method saveDownLoadSo", libPath);
                                File destFile = new File(libPath);
                                //如果存在，先删除
                                if (destFile.exists()) {
                                    destFile.delete();
                                }
                                String rpath = FlutterFileUtils.copyLibAndWrite(mcontext, npath, nfilename);
                                result.success(rpath);


                            } else if (call.method.equals("getSOPath")) {
                                // int batteryLevel = getBatteryLevel();
                                Log.d("method getSOPath", "libPath");
                                // 获取当前配置
                                File dir = this.getDir("libs", Activity.MODE_PRIVATE);
                                String dirPath = dir.getAbsolutePath() + File.separator;
                                String libPath = dirPath + "libapp_hot.so";
                                // Log.d("Current Language", currentLanguage);
                                // Log.d("Current Language", currentLanguage);
                                // Log.d("Current Language", currentLanguage);
                                Log.d("getSOPath", "getSOPath");
                                File directory = new File(dirPath);
                                File[] files = directory.listFiles();
                                if (files != null && files.length > 0) {
                                    // 遍历文件列表
                                    Log.d("getSOPath0", files.length + "");
                                    for (File file : files) {
                                        // 检查文件是否是目录
                                        if (file.isDirectory()) {
//                                            Log.d("getSOPath1", "getSOPath");
                                            Log.d("getSOPath1", file.getName());
                                        } else {
//                                            Log.d("getSOPath2", "getSOPath");
                                            Log.d("getSOPath2", file.getName());

                                        }
                                    }
                                } else {
                                    Log.d("getSOPath1", "getSOPath");
                                    Log.d("目录为空或不存在。", "");
                                }

                                result.success(libPath);

                            } else {
                                result.notImplemented();
                            }
                        });

    }
}
